const Url = require('Url.js');

const ACCESS_TOKEN_KEY = "access_token4"

function getAccessToken() {
  return wx.getStorageSync(ACCESS_TOKEN_KEY);
}

function setAccessToken(token) {
  return wx.setStorageSync(ACCESS_TOKEN_KEY, token);
}

//添加事件结束
Promise.prototype.finally = function(callback) {
  var Promise = this.constructor;
  return this.then(
    function(value) {
      Promise.resolve(callback()).then(
        function() {
          return value;
        }
      );
    },
    function(reason) {
      Promise.resolve(callback()).then(
        function() {
          throw reason;
        }
      );
    }
  );
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function initAccessToken() {
  return new Promise(function(resolve, reject) {
    let access_token = getAccessToken()
    if (access_token) {
      resolve();
      return;
    }
    console.log("wx.login")
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // console.log("code", res.code)
        wx.request({
          url: Url.getUrl('/login/accessToken'),
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            code: res.code,
          },
          fail: function(res) {
            wx.showModal({
              title: "出错了",
              content: "服务器忙，请稍候再试",
              showCancel: false,
            });
          },
          success: function(res) {
            let data = res.data
            // console.log("accessToken.success", data);
            if (data.accessToken) {
              setAccessToken(data.accessToken);
              resolve();
            }
          }
        })
      }
    })
  });
}

function post(opts) {
  opts.data = opts.data || {};
  let access_token = getAccessToken()
  if (access_token) {
    opts.data.accessToken = access_token;
  } else {
    return new Promise(function(resolve, reject) {
      initAccessToken().then(() => {
        console.log('initAccessToken.then')
        post(opts).then(data => {
          resolve(data)
        })
      })
    })
  }
  opts.method = "POST";
  if (opts.url[0] == "/") {
    opts.url = Url.getUrl(opts.url);
  }
  console.log("opts.url", opts.url)
  opts.header = {
    'content-type': 'application/x-www-form-urlencoded'
  };
  if (access_token) {
    opts.data.accessToken = access_token;
  }
  if (!opts.fail) {
    opts.fail = function(res) {
      console.log(res);
      wx.hideLoading();
      wx.showModal({
        title: "出错了",
        content: "服务器忙，请稍候再试",
        showCancel: false,
      });
    }
  }
  if (opts.success) {
    wx.request(opts);
  } else {
    return new Promise(function(resolve, reject) {
      opts.success = function(res) {
        wx.hideLoading();
        console.log("request.success", res)
        let data = res.data
        if (data.error) {
          // wx.showModal({
          //   title: "出错了",
          //   content: data.error,
          //   showCancel: false,
          // });
          wx.showToast({
            title: data.error,
            icon: 'none',
          })
        } else {
          resolve(data)
        }
      }
      if (opts.title) {
        wx.showLoading({
          title: opts.title,
          mask: true,
        })
      }
      wx.request(opts);
    });
  }
  // return new Promise((resolve, reject) => {
  //   setTimeout(() => {
  //     opts.success && opts.success(testData)
  //     resolve(testData)
  //   }, 500)
  // })
}

function alert(msg) {
  wx.showToast({
    title: msg,
    icon: 'none',
  })
}

function login(uid) {
  wx.setStorageSync('uid', uid);
}

function logout() {
  wx.removeStorageSync('uid');
}



module.exports = {
  formatDate: function(date) {
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let hour = date.getHours()
    let minute = date.getMinutes()
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
  },
  login: login,
  logout: logout,
  uploadImages: function(images) {
    return new Promise((resolve, reject) => {
      if (images == null || images.length == 0) {
        resolve([])
        return
      }
      let ajaxs = images.map(img => {
        return this.uploadFile(img)
      })
      Promise.all(ajaxs).then(res => {
        resolve(res)
      })
    })
  },
  uploadFile: function(file) {
    return new Promise(function(resolve, reject) {
      wx.uploadFile({
        url: Url.getUrl("/api/upload"),
        filePath: file,
        name: 'file',
        formData: {
          access_token: wx.getStorageSync('access_token')
        },
        success: function(res) {
          var data = res.data
          if (typeof data == "string") {
            data = JSON.parse(data)
          }
          resolve(data.data.path)
        }
      })
    })
  },
  initUploadImage: function(page) {
    page.chooseImage = () => {
      this.chooseImage(page)
    };
    page.previewImage = (e) => {
      this.previewImage(page, e.target.dataset.index)
    };
    page.removeImg = (e) => {
      this.removeImg(page, e.target.dataset.index)
    };
  },
  chooseImage: function(page) {
    console.log("chooseImage", page);
    wx.chooseImage({
      count: (page.data.maxImageNum || 9) - page.data.images.length,
      sizeType: ['compressed'],
      // sourceType: ['camera'],
      success: res => {
        let images = page.data.images,
          maxFileNum = page.data.maxFileNum;
        //images = images.concat(res.tempFilePaths.filter(_ => images.indexOf(_) < 0));
        images = images.concat(res.tempFilePaths);
        images = images.length <= maxFileNum ? images : images.slice(0, maxFileNum);
        page.setData({
          images: images
        });
      }
    });
  },
  previewImage: function(page, index) {
    console.log("previewImage", page, index);
    wx.previewImage({
      current: page.data.images[index],
      urls: page.data.images,
    });
  },
  removeImg: function(page, index) {
    console.log("removeImg", page, index);
    wx.showModal({
      title: "操作提示",
      content: "是否删除图片？",
      success: res => {
        if (res.confirm) {
          let images = page.data.images;
          images.splice(index, 1);
          page.setData({
            images: images
          });
        }
      }
    });
  },
  initSearchBar: function(page) {
    page.showInput = function() {
      page.setData({
        inputShowed: true
      });
    }
    page.hideInput = function() {
      page.setData({
        inputVal: "",
        inputShowed: false
      });
    }
    page.clearInput = function() {
      page.setData({
        inputVal: ""
      });
    }
    page.inputTyping = function(e) {
      console.log("inputTyping")
      page.setData({
        inputVal: e.detail.value
      });
    }
  }

}

module.exports = {
  getAccessToken: getAccessToken,
  formatTime: formatTime,
  post: post,
  alert: alert,
}